var pixelRatio = wx.getSystemInfoSync().pixelRatio; //设备像素比
var pic_height = 0; //图片真实高度
var pic_width = 0; //图片真实宽度
var pic_w_h_b = 0; //图片高宽比
var v_pic_width = 0; //图片放置到页面上虚拟宽度
var v_pic_height = 0; //图片放置到页面上虚拟高度
var dest_pic_width = 1080; //导出的文件的宽度
var changeCount = 0;
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.src = '/pages/audio/1.wav'

function isAllReaded(element, index, array) {
  return (element.isReaded == true);
}
let lastTempFilePath = ''
function unReaded(value) {
  return value.isReaded != true;
}
const db = wx.cloud.database()
Page({
  data: {
    pic_url: "",
    zm: {
      zh: "正在加载",
      en: "Loading"
    },
    destpic:'',
    condition: true,
    timestamp: Date.parse(new Date()) / 1000
  },
  scroll: function (e) {
    this.setData({
      scroll: e.detail,
      condition: false
    })
  },

  refresh2: function () {
    var that = this;
    var timestamp = Date.parse(new Date()) / 100;
    if (timestamp - that.data.timestamp > 7) {
      var lastzm = this.data.zm || {
        zh: "正在加载",
        en: "loading"
      };

      that.getOne();
      that.setData({
        timestamp: Date.parse(new Date()) / 100,
        lastzm: lastzm
      })
      if (changeCount >= 3) {
        try {
          console.log(wx.getStorageSync('isShowedTips'));
          var value = wx.getStorageSync('isShowedTips') != true;
          console.log(value);
          if (value) {
            that.setData({
              ashowModal: true,
              word: "摇一摇可以回退哦!",
              iconType: 2
            })
            wx.setStorage({
              key: "isShowedTips",
              data: true
            })
          }
        } catch (e) {
          console.log(e);
        }
      } else {
        changeCount++;
      }

      this.xz();

    }



  },
  getOne() {
    var _this = this;
    //检查本地是否有缓存
    try {
      var value = wx.getStorageSync('list');
      //本地是否有请求过的记录
      if (value) {
        //判断记录中是否有尚未使用过的
        if (value.every(isAllReaded)) {
          //都读完了，就把id取出来，发送给后端请求别的新数据
          var list = value.map(x => x._id);
          const _ = db.command
          db.collection('words').limit(10).where({
              // gt 方法用于指定一个 "大于" 条件，此处 _.gt(30) 是一个 "大于 30" 的条件
              _id: _.nin(list)
            })
            .get({
              success: function (res) {
                var newList = res.data;
                if (newList.length < 10) {
                  wx.removeStorage({
                    key: 'list',
                    success: function (res) {
                      _this.getOne();
                      return
                    }
                  })
                }
                var i = Math.floor((Math.random() * newList.length));
                newList[i].isReaded = true;
                value = newList.concat(value);
                wx.setStorageSync('list', value);
                _this.setData({
                  zm: newList[i]
                })
              }
            })
          
        } else {
          //把没读完的取出一条返回
          var list = value.filter(unReaded);
          console.log(list);
          var i = Math.floor((Math.random() * list.length));
          var item = list[i];
          var index = value.findIndex((v) => {
            return v._id === item._id;
          });
          console.log(value[index]);
          value[index].isReaded = true;
          wx.setStorageSync('list', value);
          _this.setData({
            zm: item
          })
        }
      } else {
        db.collection('words').limit(10)
          .get().then(res => {
            console.log(res)
            var newList = res.data;
            var i = Math.floor((Math.random() * newList.length));
            newList[i].isReaded = true;
            wx.setStorageSync('list', newList);
            _this.setData({
              zm: newList[i]
            })
          }).catch(err => {
            console.log(err)
          })

      }
    } catch (e) {
      console.log(3, e);
    }
  },
  /**
   * 保存成图片文件
   */
  save: function () {
    /**
     * 画布大小比图片高80PX
     */
    var _this = this;
    const ctx = wx.createCanvasContext('main');
    var scroll = _this.data.scroll || {
      scrollTop: 0
    };
    /**
     * 全部铺上纯黑色
     * 滚动 
     */
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, 1080, 1080 * _this.data.pic_height / _this.data.pic_width + 80);
    console.log("图片的高度是", 1080 * _this.data.pic_height / _this.data.pic_width);
    //图片放置画布左上角0，40
    ctx.drawImage(_this.data.pic_url, 0, 40, 1080, 1080 * _this.data.pic_height / _this.data.pic_width);
    ctx.fillStyle = "black";
    ctx.fillRect(0, 40, 1080, scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth);
    ctx.fillStyle = "black";
    ctx.fillRect(0, 40 + 462 + scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth, 1080, 45);
    ctx.setFontSize(30);




    // ctx.drawImage("/pages/images/waterMarker.png", 1080 - 156 - 10, scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth + 10, 156, 53);
    /**
     * 设置阴影
     * 单独设置以下功能无效，微信小程序BUG
     * shadowBlur
     * shadowColor
     * shadowOffsetX
     * shadowOffsetY
     */
    ctx.setShadow(2, 2, 2, 'black')
    //设置文字居中
    ctx.setTextAlign('center');
    ctx.setTextBaseline('middle');
    ctx.setFillStyle('white');
    /**
     * 设置中文字幕
     */
    ctx.fillText(_this.data.zm.zh, 540, scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth + 462 - 25, 1000);
    ctx.setFillStyle('white');
    /**
     * 设置英文字幕
     */
    ctx.fillText(_this.data.zm.en, 540, scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth + 462 + 5, 1000);

    /**
     * 设置水印文字
     */
    ctx.setShadow(0, 0, 0, "white");
    ctx.setFontSize(18)
    ctx.setTextAlign('right');
    ctx.setFillStyle('#999999');
    ctx.setTextBaseline('middle');
    ctx.fillText("光影制作人小程序", 1050, 20 + scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth);
    /**
     * 截取canvas中的某一块成图片
     */
    ctx.draw(true, () => {
      wx.canvasToTempFilePath({
        x: 0,
        y: scroll.scrollTop * 1080 / wx.getSystemInfoSync().screenWidth, //不用调节
        width: 1080,
        height: 462 + 80,
        destWidth: 1080,
        destHeight: 462 + 80,
        quality: 0.5,
        canvasId: 'main',
        success: function (res) {
          _this.setData({
            destpic: res.tempFilePath
          })
          /**
           * 保存到用户手机中
           */
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (res1) {
              wx.previewImage({
                urls: [res.tempFilePath]
              })
              _this.setData({
                mshowModal: true,
                word: "保存成功",
                iconType: 2
              })
            },
            fail: function (err) {
              _this.setData({
                ashowModal: true,
                word: "保存失败，长按手动保存",
                iconType: 1
              })

              wx.previewImage({
                urls: [res.tempFilePath]
              })
            }
          })
        }
      })
    });
  },
  xz: function () {
    var that = this;
    console.log(1111111111, that.adoSrc);
    innerAudioContext.play();
    //wx.vibrateLong({});
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    animation.rotate(360).step();
    this.setData({
      animationData: animation.export()
    })
    that.textFly();
    setTimeout(function () {
      animation.rotate(0).step({
        duration: 0,
        transformOrigin: "50%,50%",
        timingFunction: 'linear'
      });

      that.setData({
        animationData: animation.export()
      })
    }, 300)
  },
  /**
   * 文字飞入特效
   */
  textFly: function () {
    var that = this;
    var animation2 = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    animation2.translateX(720).step();
    this.setData({
      animationData2: animation2.export()
    })
    animation2.translateY(-720).step({
      duration: 50
    });
    animation2.translateX(-720).step({
      duration: 50
    });
    animation2.translateY(0).step({
      duration: 50
    });
    setTimeout(function () {
      animation2.translateX(0).step({
        duration: 50
      });
      this.setData({
        animationData2: animation2.export()
      })
    }.bind(this), 500)
  },
  onLoad: function (options) {
    var pic_url = options.url;
    this.setData({
      pic_url: pic_url
    })
    this.refresh2();
  },
  onReady: function () {
    var _this = this;

    wx.getImageInfo({
      src: _this.data.pic_url,
      success: function (res) {
        _this.setData({
          pic_w_h_b: res.width / res.height,
          pic_width: res.width,
          pic_height: res.height,
          v_pic_width: 750,
          v_pic_height: 750 * res.height / res.width
        })
      }
    })
  },
  getPre: function () {
    var _this = this;
    //wx.vibrateLong({});
    innerAudioContext.play();
    if (_this.data.lastzm.en != "Loading") {
      if (_this.data.lastzm.zh == _this.data.zm.zh) {
        _this.setData({
          ashowModal: true,
          word: "只能回退一次，重选一个吧",
          iconType: 1
        })

      } else {
        _this.xz();
        _this.setData({
          zm: _this.data.lastzm
        })
        _this.setData({
          mshowModal: true,
          word: "回退成功",
          iconType: 2
        })
      }

    } else {
      _this.setData({
        ashowModal: true,
        word: "没有上一个，重选一个吧",
        iconType: 1
      })
    }
  },
  onShareAppMessage: function(){
    var that = this;
    return {
      title: that.data.zm.zh,
      path: '/pages/main/main',
      imageUrl: that.data.destpic || 'https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/image/w%3D500/sign=c88bac2975f0f736d8fe4c013a54b382/b999a9014c086e067e7aa51d0f087bf40bd1cb92.jpg'
    }
  },
  onShow: function () {
    wx.startAccelerometer({})
  },
  onHide: function () {
    wx.stopAccelerometer({})
  }
})